//
//  AddressBookManager.m
//  PigMarket
//
//  Created by mac on 2019/6/26.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "AddressBookManager.h"
#import <Contacts/Contacts.h>

static AddressBookManager *instance = nil;
@implementation AddressBookManager
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[AddressBookManager alloc] init];
    });
    return instance;
}
- (void)queryAddressBookCompletionBlock:(void (^)(NSMutableArray *, NSFileManager *))completionBlock{
    if((([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) | CNAuthorizationStatusAuthorized))
    {
        NSLog(@"允许访问");
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        
        NSArray *array = @[[CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName],
                          CNContactImageDataAvailableKey,
                          CNContactPhoneNumbersKey];
        
        CNContactFetchRequest *request = [[CNContactFetchRequest alloc]initWithKeysToFetch:array];
        NSMutableArray *addressBookArray = [[NSMutableArray alloc] init];
        //存放json数据
        NSMutableArray *jsonArr = [[NSMutableArray alloc] init];

        [contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
           
            //这个block会反复调用
            AddressBookModel *model = [[AddressBookModel alloc] init];
            model.name = [NSString stringWithFormat:@"%@%@",contact.familyName ? contact.familyName : @"",
                       contact.givenName ? contact.givenName : @""];
            
            NSArray *phones = contact.phoneNumbers;
            //存储好吗
            NSMutableArray *numArr = [[NSMutableArray alloc] init];
            for (NSInteger i = 0; i < phones.count; i++)
            {
                CNLabeledValue *phone = [phones objectAtIndex:i];
                //获取电话号码
                CNPhoneNumber *phoneNum = phone.value;
                NSCharacterSet *filterString = [NSCharacterSet characterSetWithCharactersInString:@"~￥#&*<>《》()[]{}【】^@/￡¤￥|§¨「」『』￠￢￣~@#￥&*（）——+|《》$_€。.-"];
                NSString *num = [[phoneNum.stringValue componentsSeparatedByCharactersInSet: filterString]componentsJoinedByString: @""];
                [model.tels addObject:num];
                [numArr addObject:num];
            }
            
            [addressBookArray addObject:model];
            
            //json数据处理
            NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init];
            [jsonDic setValue:numArr forKey:@"phoneNum"];
            [jsonDic setValue:model.name forKey:@"name"];
            [jsonArr addObject:jsonDic];
            
        }];
        NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/temp/myJson.json"];
        NSDictionary *jsonDic = @{@"addressBook":jsonArr};
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:nil];
        [jsonData writeToFile:filePath atomically:YES];
        
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL res=[fileManager createFileAtPath:filePath contents:nil attributes:nil];
        //通过data创建数据
        [fileManager createFileAtPath:filePath contents:jsonData attributes:nil];
       
        completionBlock(addressBookArray,fileManager);
    }
    else
    {
        NSLog(@"不允许访问");
        [[AlertAction sharedInstance] showAlertWithTitle:@"提示" message:@"您未开启通讯录权限，请前往设置中心开启" confirmBtnTitle:@"确定" confirmBlock:^{
            
        } cancelBlock:^{
            
        }];
    }
}
@end

@implementation AddressBookModel
@end
